import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { debtorService } from '../utils/cloud'

export const useDebtForm = initialFormData => {
  const [formData, setFormData] = useState(initialFormData)
  const [debtors, setDebtors] = useState([])
  const [calculation, setCalculation] = useState(null)
  const [showDetails, setShowDetails] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // 从云数据库加载债务人数据
    const loadDebtors = async () => {
      try {
        setLoading(true)
        const result = await debtorService.getDebtors()
        console.log('🚀 ~ loadDebtors ~ result:', result)
        if (!result.success) {
          throw new Error(result.error)
        }
        setDebtors(result.data)
      } catch (error) {
        console.error('加载债务人数据失败:', error)
        Taro.showToast({
          title: '加载债务人数据失败',
          icon: 'error'
        })
      } finally {
        setLoading(false)
      }
    }

    loadDebtors()
  }, [])

  // 将债务人数据转换为Picker可用的格式
  const creditorOptions = debtors.map(debtor => ({
    name: `${debtor.name}(${debtor.cardNumber.slice(-4)})`,
    id: debtor._id,
    cardNumber: debtor.cardNumber
  }))

  // 处理债权人选择
  const handleCreditorChange = value => {
    const selectedCreditor = creditorOptions[value.detail.value]
    handleInputChange(selectedCreditor.id, 'creditor')
  }

  // 处理输入变化
  const handleInputChange = (value, field) => {
    const newFormData = {
      ...formData,
      [field]: value
    }

    // 如果修改了总期数或已还期数，自动计算剩余期数
    if (field === 'totalPeriods' || field === 'paidPeriods') {
      const total = parseInt(field === 'totalPeriods' ? value : formData.totalPeriods) || 0
      const paid = parseInt(field === 'paidPeriods' ? value : formData.paidPeriods) || 0
      newFormData.remainingPeriods = Math.max(0, total - paid).toString()
    }

    setFormData(newFormData)
  }

  // 保存数据
  const handleSubmit = (calculation, onSuccess) => {
    if (!formData.creditor || !calculation) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    const debtData = {
      ...formData,
      calculation,
      createTime: new Date().toISOString()
    }

    // 保存到云数据库
    debtorService
      .addDebt(debtData)
      .then(result => {
        if (result.success) {
          Taro.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              setTimeout(() => {
                onSuccess?.()
              }, 2000)
            }
          })
        } else {
          throw new Error(result.error)
        }
      })
      .catch(error => {
        console.error('保存失败:', error)
        Taro.showToast({
          title: '保存失败',
          icon: 'error'
        })
      })
  }

  return {
    formData,
    setFormData,
    debtors,
    creditorOptions,
    calculation,
    setCalculation,
    showDetails,
    setShowDetails,
    handleCreditorChange,
    handleInputChange,
    handleSubmit,
    loading
  }
}
